﻿// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone

using BlazorAdmin.Models;
using BlazorAdmin.Interface;
using BootstrapBlazor.Components;
using BlazorAdmin.Web.Shared.Extensions;
using BlazorAdmin.Web.Shared.Providers;
using BlazorAdmin.Web.Shared.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Routing;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;

namespace Pangeo.Admin.Web.Shared
{
    /// <summary>
    /// 主窗体
    /// </summary>
    public partial class MainLayout : IDisposable
    {
        private readonly bool AppIsLock = false;
        private const int LockInterval = 100 * 1000;

        [CascadingParameter(Name = "ClientInfo")]
        public ClientInfo Client { get; set; }

        [NotNull]
        private User? currentUser = null;
        private IEnumerable<MenuItem>? menuItems = null;

        #region Override

        protected override async Task OnInitializedAsync()
        {
            //var authState = AuthStateProvider.GetAuthenticationStateAsync().Result;
            //if (authState.User != null && authState.User.Identity.IsAuthenticated)
            //{
            //
            //}
            //else
            //{
            //    //未登录
            //}

            base.OnInitialized();

            currentUser = AppContext.CurrentUser;
            string? userName = currentUser?.UserName;
            menuItems = NavigationsService.GetAllMenus(userName).ToMenus();
            NavigationManager.LocationChanged += NavigationManager_LocationChanged;
        }

        private void NavigationManager_LocationChanged(object? sender, LocationChangedEventArgs e)
        {
            BlazorAdmin.Models.Trace log = new()
            {
                UserName = AppContext.LoginName,
                IP = Client.Ip,
                RequestUrl = e.Location.Substring(e.Location.IndexOf("/", 8)),
                UserAgent = Client.UserAgent,
            };

            ThreadPool.QueueUserWorkItem(state => TraceService.Log(log));

            Debug.WriteLine($"{sender} - {e.Location}", "NavigationManager_LocationChanged");
        }

        #endregion

        private void OnLogout()
        {
            if (AuthStateProvider is AuthenticationProvider authProvider)
            {
                AppContext.CurrentUser = null;
                authProvider.MarkUserAsLoggedOut();
            }
        }

        #region IDisposable

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                NavigationManager.LocationChanged -= NavigationManager_LocationChanged;
            }
        }

        #endregion

        #region Inject

        [Inject]
        [NotNull]
        private INavigation? NavigationsService { get; set; }

        [Inject]
        [NotNull]
        private NavigationManager? NavigationManager { get; set; }

        [Inject]
        [NotNull]
        private AuthenticationStateProvider? AuthStateProvider { get; set; }

        [Inject]
        [NotNull]
        public BootstrapAppContext? AppContext { get; set; }

        [Inject]
        [NotNull]
        private ITrace TraceService { get; set; }

        #endregion
    }
}
